package com.zy.composeworld.base

import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MotionEvent
import androidx.activity.OnBackPressedCallback
import androidx.viewbinding.ViewBinding
import com.zy.composeworld.ktx.toast
import com.zy.composeworld.utils.ZLog.d
import java.lang.reflect.ParameterizedType

abstract class BaseActivity<VB : ViewBinding> : AppCompatActivity() {


    val TAG: String = this::class.java.simpleName

    protected lateinit var binding: VB


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                onBack()
            }
        })

        d("BaseActivity", "javaClass Test ------------------start")
        d("BaseActivity", "javaClass:$javaClass")
        d("BaseActivity", "javaClass.genericSuperclass:${javaClass.genericSuperclass}")
        d(
            "BaseActivity",
            "javaClass.genericSuperclass is ParameterizedType:${javaClass.genericSuperclass is ParameterizedType}"
        )
        d("BaseActivity", "javaClass Test ------------------end")

        if (false) {
            //正常情况
            //2023-12-23 18:46:50.492 16973-16973 ZYDebug                 com.zy.world                         D  BaseActivity javaClass Test ------------------start
            //2023-12-23 18:46:50.492 16973-16973 ZYDebug                 com.zy.world                         D  BaseActivity javaClass:class com.zy.world.MainActivity
            //2023-12-23 18:46:50.492 16973-16973 ZYDebug                 com.zy.world                         D  BaseActivity javaClass.genericSuperclass:com.zy.activity.BaseActivity<com.zy.world.databinding.ActivityMainBinding>
            //2023-12-23 18:46:50.492 16973-16973 ZYDebug                 com.zy.world                         D  BaseActivity javaClass.genericSuperclass is ParameterizedType:true
            //2023-12-23 18:46:50.492 16973-16973 ZYDebug                 com.zy.world                         D  BaseActivity javaClass Test ------------------end
            //异常情况
            //2023-12-23 18:47:15.945 16973-16973 ZYDebug                 com.zy.world                         D  BaseActivity javaClass Test ------------------start
            //2023-12-23 18:47:15.945 16973-16973 ZYDebug                 com.zy.world                         D  BaseActivity javaClass:class com.zy.test.animation.AnimationMenuActivity
            //2023-12-23 18:47:15.945 16973-16973 ZYDebug                 com.zy.world                         D  BaseActivity javaClass.genericSuperclass:class com.zy.composeworld.base.BaseMenuActivity
            //2023-12-23 18:47:15.945 16973-16973 ZYDebug                 com.zy.world                         D  BaseActivity javaClass.genericSuperclass is ParameterizedType:false
            //2023-12-23 18:47:15.945 16973-16973 ZYDebug                 com.zy.world                         D  BaseActivity javaClass Test ------------------end
            //2023-12-23 18:47:15.947 16973-16973 AndroidRuntime          com.zy.world                         E  FATAL EXCEPTION: main
            //                                                                                                    Process: com.zy.world, PID: 16973
            //                                                                                                    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.zy.world/com.zy.test.animation.AnimationMenuActivity}: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
            //                                                                                                    	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4065)
            //                                                                                                    	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4252)
            //                                                                                                    	at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
            //                                                                                                    	at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
            //                                                                                                    	at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
            //                                                                                                    	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2618)
            //                                                                                                    	at android.os.Handler.dispatchMessage(Handler.java:110)
            //                                                                                                    	at android.os.Looper.loop(Looper.java:219)
            //                                                                                                    	at android.app.ActivityThread.main(ActivityThread.java:8673)
            //                                                                                                    	at java.lang.reflect.Method.invoke(Native Method)
            //                                                                                                    	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
            //                                                                                                    	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1109)
            //                                                                                                    Caused by: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
            //                                                                                                    	at com.zy.activity.BaseActivity.onCreate(BaseActivity.kt:25)
            //                                                                                                    	at com.zy.test.animation.AnimationMenuActivity.onCreate(AnimationMenuActivity.java:18)
            //                                                                                                    	at android.app.Activity.performCreate(Activity.java:8214)
            //                                                                                                    	at android.app.Activity.performCreate(Activity.java:8202)
            //                                                                                                    	at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1320)
            //                                                                                                    	at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4038)
            //                                                                                                    	at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4252) 
            //                                                                                                    	at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91) 
            //                                                                                                    	at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149) 
            //                                                                                                    	at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103) 
            //                                                                                                    	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2618) 
            //                                                                                                    	at android.os.Handler.dispatchMessage(Handler.java:110) 
            //                                                                                                    	at android.os.Looper.loop(Looper.java:219) 
            //                                                                                                    	at android.app.ActivityThread.main(ActivityThread.java:8673) 
            //                                                                                                    	at java.lang.reflect.Method.invoke(Native Method) 
            //                                                                                                    	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513) 
            //                                                                                                    	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1109) 

            //如果
            (javaClass.genericSuperclass as ParameterizedType).let {
                it.actualTypeArguments.let { types ->
                    binding =
                        (types[0] as Class<VB>).getMethod("inflate", LayoutInflater::class.java)
                            .invoke(null, layoutInflater) as VB
                }
            }
            // TODO: Fixme 子类的子类存在问题
        } else {
            binding = getViewBinding()
        }

        setContentView(binding.root)
        binding.initViewBinding()
    }

    /**
     * 上次点击返回键的时间
     */
    private var lastBackPressTime = -1L


    open fun onBack() {
        if (true) {
            finish()
            return
        }
        val currentTIme = System.currentTimeMillis()
        if (lastBackPressTime == -1L || currentTIme - lastBackPressTime >= 2000) {
            // 显示提示信息
            showBackPressTip()
            // 记录时间
            lastBackPressTime = currentTIme
        } else {
            //退出应用
            finish()
            // android.os.Process.killProcess(android.os.Process.myPid())
            // System.exit(0) // exitProcess(0)
            // moveTaskToBack(false)
        }
    }

    private fun showBackPressTip() {
        toast("再按一次退出$this")
    }

    /**
     * 状态栏颜色
     */
    open fun statusBarColor(): Int = Color.BLACK

    /**
     * 状态栏颜色
     */
    protected open fun navigationBarColor(): Int = Color.BLACK

    /**
     * 是否沉浸式
     */
    protected open fun isImmersion(): Boolean = true

    /**
     * 状态栏模式
     * @return true 字体黑色，背景亮色  false 字体白色，背景暗色
     */
    protected open fun lightMode(): Boolean = true


    abstract fun getViewBinding(): VB

    abstract fun VB.initViewBinding()


    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        d("BaseActivity", "dispatchKeyEvent:$event")
        return super.dispatchKeyEvent(event)
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        //ZLog.d("BaseMainActivity", "dispatchTouchEvent:" + ev);
        //ZLog.d("BaseMainActivity", "dispatchTouchEvent "+ev.getAction()+" 相对坐标:[" + ev.getX() + "," + ev.getY() + "] 绝对坐标:[" + ev.getRawX() + "," + ev.getRawY() + "]");
        return super.dispatchTouchEvent(ev)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        val result = super.onTouchEvent(event)
        d("BaseActivity", "onTouchEvent result:$result")
        return super.onTouchEvent(event)
    }
}

